package proj.pt.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import proj.pt.model.Course;
import proj.pt.model.SubCourse;
import proj.pt.model.Subject;
import proj.pt.model.SubjectAllotment;
import proj.pt.model.User;

public class SubjectAllotmentController extends CustomSimpleFormController {

	protected Object formBackingObject(HttpServletRequest request)
    throws Exception{
		// getting the id from the request, if it is supplied as parameter.
		// else -1 will be set.
		long id = ServletRequestUtils.getLongParameter(request, "id", -1);
		
		// if id value is greater than -1, then requesting to lead an already existing from database,
		// else create a new object.
		SubjectAllotment allotment = null;
		if(id > -1){
			// load from database
			allotment = getLogicProcessor().getSubjectAllotment(new Long(id));
		} //end if
		
		// there may be chance that false id has given for loading from database, and that is not present there, so  will be null;
		if(allotment == null)
		return new SubjectAllotment();
		else return allotment;
	}
	
	
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		Map dataMap = super.referenceData(request, command, errors);
		
		SubjectAllotment allotment = (SubjectAllotment)command;
		String action = WebUtils.getAction(request);
		
		if("action_course_select".equals(action)){
			// course selected, so load batches and semesters according to that.
			dataMap.put("batches", getLogicProcessor().getCourseBatches(allotment.getCourse()));
			dataMap.put("semesters", getLogicProcessor().getSubCourses(allotment.getCourse()));
			
		} else if(allotment.getSubCourse() != null){
			// semester already available as selected, so retain the batches and semester list
			// as per this selection.
			if(allotment.getSubCourse().getCourse() != null)
				allotment.setCourse(getLogicProcessor().getCourse(allotment.getSubCourse().getCourse().getId()));
			
			dataMap.put("batches", getLogicProcessor().getCourseBatches(allotment.getSubCourse().getCourse()));
			dataMap.put("semesters", getLogicProcessor().getSubCourses(allotment.getSubCourse().getCourse()));
			dataMap.put("subjects", getLogicProcessor().getSubjectBySemester(allotment.getSubCourse()));
			
		} //end else if
		
			
		User currentUser = (User)dataMap.get("currentUser");
		dataMap.put("courses", getLogicProcessor().getCourses(currentUser));
		dataMap.put("tutors", getLogicProcessor().getStaff(currentUser));
		
		return dataMap;
	} //end referenceData
	
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(SubCourse.class, "subCourse", new SubCourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Course.class, "course", new CourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Subject.class, "subject", new SubjectEditor(getLogicProcessor()));
		binder.registerCustomEditor(User.class, "tutor", new UserEditor(getLogicProcessor()));
	}
	
	
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// f no validation required, then just return from this method.
		if(!doValidate(request))return;
		
		SubjectAllotment allotment = (SubjectAllotment)command;
		
		if(allotment.getTutor() == null){
			errors.reject("tutor.required", "Tutor required");
		} //end if
		
		if(allotment.getSubCourse() == null){
			errors.reject("semester.required", "Semester required");
		}
		
		if(!StringUtils.hasLength(allotment.getBatchYear())){
			errors.reject("batch.required", "Batch required");
		} //end if
		
		if(allotment.getSubject() == null){
			errors.reject("subject.required", "Subject required");
		}
		
		// look for allotment duplication.
		
	}
	
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)
     throws Exception {
		
		String action = WebUtils.getAction(request);
					
		if("action_save".equals(action)){
			getLogicProcessor().saveOrUpdateSubjectAllotment((SubjectAllotment)command);
		} else if("action_delete".equals(action)){
			getLogicProcessor().deleteSubjectAllotment((SubjectAllotment)command);
		} else if("action_cancel".equals(action)){
			// do nothing
		} else{
			// do nothing.
		} 
		
		ModelAndView  mav = new ModelAndView();
		mav.setView(new RedirectView(getSuccessURI()));
		return mav;
	} //end onSubmit
	
	
}
